<template>
    <div class="chat-container">
        <!-- 左侧会话列表 -->
        <div class="conversation-list">
            <div class="list-header">当前会话</div>
            <div class="list-content">
                <div v-for="conversation in sortedConversations" :key="conversation.conversationId" class="conversation-item"
                    :class="{ 
                        active: currentConversation?.conversationId === conversation.conversationId,
                        'has-unread': conversation.unreadCount > 0
                    }"
                    @click="selectConversation(conversation)">
                    <div class="avatar">
                        <el-avatar :size="40" :icon="User" />
                        <div v-if="conversation.unreadCount > 0" class="unread-badge">
                            {{ conversation.unreadCount }}
                        </div>
                    </div>
                    <div class="info">
                        <div class="name-time">
                            <span class="name">{{ conversation.customerName }}</span>
                            <span class="time">{{ formatTime(getLastMessageTime(conversation)) }}</span>
                        </div>
                        <div class="preview" :class="{ 'important-message': getLastMessage(conversation).isImportant }">
                            {{ getLastMessage(conversation).content }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧内容区 -->
        <div class="content-container">
            <!-- 头部 -->
            <div class="header">
                <div class="customer-info">
                    <span class="title">{{ currentConversation?.customerName }}</span>
                </div>
                <div class="actions">
                    <el-button type="primary" @click="createWorkOrder">创建工单</el-button>
                    <el-button @click="blockUser">拉黑</el-button>
                </div>
            </div>

            <!-- 主体内容区 -->
            <div class="main-content">
                <!-- 聊天区域 -->
                <div class="chat-area">
                    <div class="messages" ref="messagesContainer">
                        <div v-for="(message, index) in currentConversation?.messages" :key="index" class="message"
                            :class="[message.type, { 'important-message': message.isImportant }]">
                            <div class="message-avatar">
                                <el-avatar :size="40" :icon="User" />
                            </div>
                            <div class="message-content">
                                <div class="text">
                                    <div class="message-header" v-if="message.isImportant">
                                        <el-tag size="small" type="warning">重要</el-tag>
                                    </div>
                                    {{ message.content }}
                                </div>
                                <div class="time">{{ formatTime(message.timestamp) }}</div>
                            </div>
                            <div class="message-actions" v-if="message.type === 'user'">
                                <el-button type="text" @click="toggleImportant(index)">
                                    {{ message.isImportant ? '取消重要' : '标记重要' }}
                                </el-button>
                            </div>
                        </div>
                    </div>

                    <!-- 输入区域 -->
                    <div class="input-area">
                        <el-input v-model="newMessage" type="textarea" :rows="3" placeholder="请输入消息..." />
                        <div class="send-actions">
                            <el-button type="primary" @click="sendMessage">发送</el-button>
                        </div>
                    </div>
                </div>

                <!-- 右侧信息栏 -->
                <div class="info-panel">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="资料" name="info">
                            <!-- 访客信息 -->
                            <div class="info-section">
                                <h4>访客信息</h4>
                                <div class="info-item">
                                    <span class="label">IP</span>
                                    <span>{{ currentConversation?.visitorInfo?.ip }}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">浏览器</span>
                                    <span>{{ currentConversation?.visitorInfo?.browser }}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">首次访问</span>
                                    <span>{{ currentConversation?.visitorInfo?.firstVisit ? '是' : '否' }}</span>
                                </div>
                            </div>
                            <!-- 客户信息 -->
                            <div class="info-section">
                                <h4>客户信息</h4>
                                <div class="info-item">
                                    <span class="label">电话</span>
                                    <span>{{ currentConversation?.customerInfo?.phone || '—' }}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">邮箱</span>
                                    <span>{{ currentConversation?.customerInfo?.email || '—' }}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">公司</span>
                                    <span>{{ currentConversation?.customerInfo?.company || '—' }}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">来源</span>
                                    <span>{{ currentConversation?.customerInfo?.source || '—' }}</span>
                                </div>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="常用语" name="common">
                            常用语内容
                        </el-tab-pane>
                        <el-tab-pane label="历史工单" name="history">
                            历史工单内容
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { User } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const conversations = ref([])
const currentConversation = ref(null)
const newMessage = ref('')
const activeTab = ref('info')
const messagesContainer = ref(null)
let pollingInterval = null // 用于存储轮询定时器

// 计算属性：对会话进行排序（新消息置顶）
const sortedConversations = computed(() => {
    return [...conversations.value].sort((a, b) => {
        const aTime = getLastMessageTime(a)
        const bTime = getLastMessageTime(b)
        return new Date(bTime) - new Date(aTime)
    })
})

// 获取最后一条消息的时间
const getLastMessageTime = (conversation) => {
    if (!conversation.messages || conversation.messages.length === 0) {
        return conversation.startTime
    }
    return conversation.messages[conversation.messages.length - 1].timestamp
}

// 获取最后一条消息
const getLastMessage = (conversation) => {
    if (!conversation.messages || conversation.messages.length === 0) {
        return { content: '暂无消息', isImportant: false }
    }
    const lastMessage = conversation.messages[conversation.messages.length - 1]
    return {
        content: lastMessage.content,
        isImportant: lastMessage.isImportant || false
    }
}

// 标记消息为重要
const toggleImportant = (messageIndex) => {
    if (currentConversation.value && currentConversation.value.messages[messageIndex]) {
        currentConversation.value.messages[messageIndex].isImportant = 
            !currentConversation.value.messages[messageIndex].isImportant
    }
}

// 选择会话时清除未读计数
const selectConversation = (conversation) => {
    if (conversation.unreadCount) {
        conversation.unreadCount = 0
    }
    currentConversation.value = conversation
    scrollToBottom()
}

// 获取会话列表
const getConversations = async () => {
    try {
        const response = await axios.get('http://localhost:3000/api/conversations')
        const newData = response.data.data

        if (conversations.value.length === 0) {
            // 初始化未读计数
            newData.forEach(conv => conv.unreadCount = 0)
            conversations.value = newData
            if (newData.length > 0) {
                selectConversation(newData[0])
            }
            return
        }

        newData.forEach(newConv => {
            const existingConv = conversations.value.find(conv => conv.conversationId === newConv.conversationId)
            if (existingConv) {
                // 检查是否有新消息
                if (newConv.messages.length > existingConv.messages.length) {
                    const newMessageCount = newConv.messages.length - existingConv.messages.length
                    // 如果不是当前选中的会话，增加未读计数
                    if (currentConversation.value?.conversationId !== newConv.conversationId) {
                        existingConv.unreadCount = (existingConv.unreadCount || 0) + newMessageCount
                    }
                    
                    if (currentConversation.value?.conversationId === newConv.conversationId) {
                        currentConversation.value = newConv
                        scrollToBottom()
                    }
                    // 保持现有的未读计数
                    newConv.unreadCount = existingConv.unreadCount || 0
                    Object.assign(existingConv, newConv)
                }
            } else {
                // 新会话默认有一条未读消息
                newConv.unreadCount = 1
                conversations.value.unshift(newConv)
                ElMessage.info(`新会话: ${newConv.customerName}`)
            }
        })
    } catch (error) {
        console.error('Error fetching conversations:', error)
    }
}

// 发送消息
const sendMessage = async () => {
    if (!newMessage.value.trim() || !currentConversation.value) return

    try {
        const response = await axios.post('http://localhost:3000/api/conversations/sendMessage', {
            conversationId: currentConversation.value.conversationId,
            content: newMessage.value
        })

        if (response.data.code === 200) {
            // 更新本地消息列表
            currentConversation.value.messages.push(response.data.data)
            newMessage.value = ''
            scrollToBottom()
            
            // 更新会话列表中的最后一条消息
            const conversationIndex = conversations.value.findIndex(
                conv => conv.conversationId === currentConversation.value.conversationId
            )
            if (conversationIndex !== -1) {
                conversations.value[conversationIndex] = currentConversation.value
            }
        } else {
            ElMessage.error('发送失败')
        }
    } catch (error) {
        console.error('Error sending message:', error)
        ElMessage.error('发送失败，请重试')
    }
}

// 格式化时间
const formatTime = (timestamp) => {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 滚动到底部
const scrollToBottom = () => {
    if (messagesContainer.value) {
        setTimeout(() => {
            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }, 100)
    }
}

// 开始轮询
const startPolling = () => {
    // 每 3 秒获取一次数据
    pollingInterval = setInterval(getConversations, 3000)
}

// 停止轮询
const stopPolling = () => {
    if (pollingInterval) {
        clearInterval(pollingInterval)
        pollingInterval = null
    }
}

// 创建工单
const createWorkOrder = () => {
    // 实现创建工单逻辑
}

// 拉黑用户
const blockUser = () => {
    // 实现拉黑用户逻辑
}

onMounted(() => {
    getConversations() // 初始获取数据
    startPolling() // 开始轮询
})

onUnmounted(() => {
    stopPolling() // 组件卸载时停止轮询
})
</script>

<style scoped>
.chat-container {
    display: flex;
    height: 100vh;
    background: #f5f7fa;
}

.conversation-list {
    width: 25%;
    border-right: 1px solid #e6e6e6;
    background: #fff;
    display: flex;
    flex-direction: column;
}

.list-header {
    padding: 16px;
    font-size: 16px;
    border-bottom: 1px solid #e6e6e6;
}

.list-content {
    flex: 1;
    overflow-y: auto;
}

.conversation-item {
    display: flex;
    padding: 12px;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;
}

.conversation-item:hover {
    background: #f5f7fa;
}

.conversation-item.active {
    background: #e6f7ff;
}

.conversation-item.has-unread {
    background: #f0f9ff;
}

.avatar {
    position: relative;
    margin-right: 12px;
}

.unread-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #f56c6c;
    color: white;
    border-radius: 50%;
    min-width: 16px;
    height: 16px;
    line-height: 16px;
    text-align: center;
    font-size: 12px;
    padding: 0 4px;
}

.info {
    flex: 1;
}

.name-time {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
}

.name {
    font-weight: 500;
}

.time {
    color: #999;
    font-size: 12px;
}

.preview {
    color: #666;
    font-size: 13px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.preview.important-message {
    color: #e6a23c;
    font-weight: 500;
}

.content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.header {
    padding: 16px;
    background: #fff;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.main-content {
    flex: 1;
    display: flex;
    overflow: hidden;
}

.chat-area {
    flex: 3;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-right: 1px solid #e6e6e6;
}

.messages {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
}

.message {
    display: flex;
    margin-bottom: 16px;
    position: relative;
}

.message.user {
    flex-direction: row-reverse;
}

.message-content {
    max-width: 70%;
    margin: 0 12px;
}

.message-content .text {
    padding: 12px;
    border-radius: 4px;
    background: #f5f7fa;
}

.message.user .message-content .text {
    background: #e6f7ff;
}

.message.important-message .text {
    border: 1px solid #e6a23c;
}

.message-content .time {
    margin-top: 4px;
    font-size: 12px;
    color: #999;
    text-align: right;
}

.message-header {
    margin-bottom: 4px;
}

.message-actions {
    position: absolute;
    right: 100%;
    top: 0;
    margin-right: 8px;
    opacity: 0;
    transition: opacity 0.3s;
}

.message:hover .message-actions {
    opacity: 1;
}

.input-area {
    padding: 16px;
    border-top: 1px solid #e6e6e6;
}

.send-actions {
    margin-top: 8px;
    display: flex;
    justify-content: flex-end;
}

.info-panel {
    flex: 1;
    padding: 16px;
    background: #fff;
}

.info-section {
    margin-bottom: 24px;
}

.info-section h4 {
    margin-bottom: 16px;
    color: #333;
}

.info-item {
    display: flex;
    margin-bottom: 12px;
}

.info-item .label {
    width: 80px;
    color: #666;
}

:deep(.el-tabs__item) {
    font-size: 14px;
}

:deep(.el-button--primary) {
    background-color: #409EFF;
}
</style>